<template>
  <div class="login-page">
    <div class="login-bg"></div>

    <div class="login-card">
      <div class="login-logo">
        <el-icon :size="48" color="#409EFF">
          <Key />
        </el-icon>
        <h1>系统登录</h1>
      </div>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          class="login-form">
        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              autocomplete="off">
            <template #prefix>
              <el-icon color="#909399">
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              autocomplete="off"
          >
            <template #prefix>
              <el-icon color="#909399">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock, Key } from '@element-plus/icons-vue';
import { login } from '../api/login';
import { useRouter } from 'vue-router';

// 解析JWT token获取用户名
const parseJwt = (token) => {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
        window.atob(base64)
            .split('')
            .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
            .join('')
    );
    return JSON.parse(jsonPayload);
  } catch (e) {
    console.error('解析token失败:', e);
    return null;
  }
};

const router = useRouter()
const formRef = ref(null);
const loading = ref(false);

const form = reactive({
  username: '',
  password: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 15, message: '用户名长度在 2-15 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    const response = await login(form);

    if (response.code === 200) {
      ElMessage.success('登录成功！');
      const token = response.data; // 后端返回的data是token字符串
      localStorage.setItem('token', token);

      // 解析token获取用户名，若失败则使用表单输入的用户名
      const payload = parseJwt(token);
      const username = payload?.username || form.username;
      localStorage.setItem('username', username);

      router.push('/home');
    } else {
      ElMessage.error(response.msg || '登录失败');
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error('网络错误，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-page {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #e0f7fa 0%, #e0f2f1 100%);
  z-index: 1;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 30px;
  z-index: 2;
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo h1 {
  margin: 15px 0 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.login-form {
  width: 100%;
}

.form-actions {
  margin-top: 15px;
}

.login-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}
</style>